# -*- coding: utf-8 -*-
# @Time    : 2024/11/10 14:01
# @Author  : CHNJX
# @File    : base_steps.py
# @Desc    :

# api/routes/base_step_routes.py
from flask import Blueprint, request
from app.model import BaseStep, db
from app.utils.response_handler import response_with_handler, success_response, error_response
from flask import current_app
base_step_bp = Blueprint('base_step', __name__)


# 获取全部基础步骤
@base_step_bp.route('/', methods=['GET'])
@response_with_handler
def get_all_steps():
    steps = BaseStep.query.all()
    return success_response([step.to_dict() for step in steps])

@base_step_bp.route('/module/<int:module_id>', methods=['GET'])
@response_with_handler
def get_steps_by_module(module_id):
    """获取指定模块的所有基础步骤"""
    steps = BaseStep.get_steps_by_module(module_id)
    return success_response([step.to_dict() for step in steps])


@base_step_bp.route('/<int:step_id>', methods=['GET'])
@response_with_handler
def get_step(step_id):
    """获取单个基础步骤"""
    step = BaseStep.query.get(step_id)
    if step is None:
        return error_response("基础步骤不存在", code=404)
    return success_response(step.to_dict())


@base_step_bp.route('/', methods=['POST'])
@response_with_handler
def create_step():
    """创建基础步骤"""
    data = request.get_json()
    required_fields = ['module_id', 'step_name', 'step_type']
    if not data or not all(field in data for field in required_fields):
        return error_response(f"缺少必要的参数: {', '.join(required_fields)}", code=400)

    try:
        step = BaseStep.create_base_step(data)
        return success_response(step.to_dict(), "基础步骤创建成功")
    except ValueError as e:
        return error_response(str(e), code=400)


@base_step_bp.route('/<int:step_id>', methods=['PUT'])
@response_with_handler
def update_step(step_id):
    """更新基础步骤"""
    step = BaseStep.query.get(step_id)
    if step is None:
        current_app.logger.error(f"基础步骤不存在: {step_id}")
        return error_response("基础步骤不存在", code=404)

    data = request.get_json()
    try:
        updated_step = step.update_base_step(data)
        current_app.logger.info(
            f"基础步骤更新成功: {updated_step.to_dict()}"
        )
        return success_response(updated_step.to_dict(), "基础步骤更新成功")
    except ValueError as e:
        current_app.logger.error(f"更新基础步骤时发生错误: {str(e)}")
        return error_response(str(e), code=400)
    except Exception as e:
        current_app.logger.error(f"更新基础步骤时发生未知错误: {str(e)}")
        return error_response("更新基础步骤失败", code=500)


@base_step_bp.route('/<int:step_id>', methods=['DELETE'])
@response_with_handler
def delete_step(step_id):
    """删除基础步骤"""
    step = BaseStep.query.get(step_id)
    if step is None:
        return error_response("基础步骤不存在", code=404)
    try:
        db.session.delete(step)
        db.session.commit()
        return success_response(message="基础步骤删除成功")
    except Exception as e:
        db.session.rollback()
        # 记录详细的错误信息
        current_app.logger.error(f"删除基础步骤时发生错误: {str(e)}")
        # 检查是否存在外键约束
        if "foreign key constraint" in str(e).lower():
            return error_response("无法删除该基础步骤,因为它被其他数据引用", code=400)
        # 检查数据库连接问题
        elif "connection" in str(e).lower():
            return error_response("数据库连接错误,请稍后重试", code=500)
        # 其他未知错误
        else:
            return error_response(f"删除失败: {str(e)}", code=500)


@base_step_bp.route('/types', methods=['GET'])
@response_with_handler
def get_step_types():
    """获取所有步骤类型"""
    types = BaseStep.get_step_types()
    return success_response(types)


@base_step_bp.route('/batch', methods=['POST'])
@response_with_handler
def batch_create_steps():
    """批量创建基础步骤"""
    data = request.get_json()
    if not isinstance(data, list):
        return error_response("请求数据必须是数组格式", code=400)

    created_steps = []
    for item in data:
        required_fields = ['module_id', 'step_name', 'step_type']
        if not all(field in item for field in required_fields):
            return error_response(f"每个步骤都必须包含以下字段: {', '.join(required_fields)}", code=400)

        try:
            step = BaseStep.create_base_step(item)
            created_steps.append(step.to_dict())
        except Exception as e:
            return error_response(f"创建步骤失败: {str(e)}", code=500)

    return success_response(created_steps, "批量创建基础步骤成功")